package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.DashboardMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.domain.Log;
import com.tanhua.model.domain.ResultDate;
import com.tanhua.model.vo.DashboardVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DashboardService {

    @Autowired
    private DashboardMapper dashboardMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;


    //概要统计信息
    public DashboardVo summary(){
        //今天日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //上周日期
        String lastweek = DateUtil.lastWeek().toString("yyyy-MM-dd");
        //上月日期
        String lastmonth = DateUtil.lastMonth().toString("yyyy-MM-dd");
        //1.累计用户
        Integer sum = analysisMapper.sum();
        //2.过去三十天活跃用户
        Integer month = analysisMapper.activePassMonth(todayStr, lastmonth);
        //3.过去七天活跃用户
        Integer week = analysisMapper.activePassWeek(todayStr, lastweek);
        //4.1今日新增用户
        Integer newCount = analysisMapper.registered(todayStr);
        //4.2上月新增用户
        Integer lastWeekCount = analysisMapper.registered(lastmonth);
        //4.3新增用户环比
        BigDecimal newRate = computeRate(newCount.longValue(), lastWeekCount.longValue());
        //5.1今日登录次数
        Integer loginCount = analysisMapper.login(todayStr);
        //5.2上月登录次数
        Integer lastLoginCount = analysisMapper.login(lastmonth);
        //5.3登录环比
        BigDecimal loginRate = computeRate(loginCount.longValue(), lastLoginCount.longValue());
        //6.1今日活跃用户
        Integer activeCount = analysisMapper.active(todayStr);
        //6.2上月活跃用户
        Integer lastActiveCount = analysisMapper.active(lastmonth);
        //6.3活跃用户环比
        BigDecimal activeRate = computeRate(activeCount.longValue(), lastActiveCount.longValue());
        //7、保存数据
        DashboardVo vo = new DashboardVo();
        vo.setCumulativeUsers(sum);
        vo.setActivePassMonth(month);
        vo.setActivePassWeek(week);
        vo.setNewUsersToday(newCount);
        vo.setNewUsersTodayRate(newRate.intValue());
        vo.setLoginTimesToday(loginCount);
        vo.setLoginTimesTodayRate(loginRate.intValue());
        vo.setActiveUsersToday(activeCount);
        vo.setActiveUsersTodayRate(activeRate.intValue());
        dashboardMapper.insert(vo);
        return vo;
    }

    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }

    //新增、活跃用户、次日留存率
    public Map users(Map map) throws ParseException {
        //今年时间
        String sd = (String) map.get("sd");
        Date date1 = new Date();
        date1.setTime(Long.valueOf(sd));
        String format1 = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        Date begin = new SimpleDateFormat("yyyy-MM-dd").parse(format1);
        String ed = (String) map.get("ed");
        Date date2 = new Date();
        date2.setTime(Long.valueOf(ed));
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(date2);
        Date end = new SimpleDateFormat("yyyy-MM-dd").parse(format2);
        String type = (String) map.get("type");

        //去年时间
        Calendar c = Calendar.getInstance();
        Calendar d = Calendar.getInstance();
        c.setTime(begin);
        c.add(Calendar.YEAR,-1);
        Date lastBegin = c.getTime();
        d.setTime(end);
        d.add(Calendar.YEAR,-1);
        Date lastEnd = d.getTime();


        //1.新增用户
        if (begin.after(end)){
            throw new BusinessException("亲,这样不合适哦");
        }
        if (begin!=null&&end!=null&&"101".equals(type)&&begin.before(end)){
            //今年
            LambdaQueryWrapper<Analysis> qw1 = new LambdaQueryWrapper<>();
            qw1.between(Analysis::getRecordDate,begin,end);
            List<Analysis> list = analysisMapper.selectList(qw1);
            List<ResultDate> newList = new ArrayList<>();
            for (Analysis analysis : list) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumRegistered());
                newList.add(rd);
            }
            //去年
            LambdaQueryWrapper<Analysis> qw2 = new LambdaQueryWrapper<>();
            qw2.between(Analysis::getRecordDate,lastBegin,lastEnd);
            List<Analysis> lastList = analysisMapper.selectList(qw2);
            List<ResultDate> oldList = new ArrayList<>();
            for (Analysis analysis : lastList) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumRegistered());
                oldList.add(rd);
            }
            Map result = new HashMap();
            result.put("thisYear",newList);
            result.put("lastYear",oldList);
            return result;
        }

        //2.活跃用户
        if (begin!=null&&end!=null&&"102".equals(type)&&begin.before(end)){
            //今年
            LambdaQueryWrapper<Analysis> qw1 = new LambdaQueryWrapper<>();
            qw1.between(Analysis::getRecordDate,begin,end);
            List<Analysis> list = analysisMapper.selectList(qw1);
            List<ResultDate> newList = new ArrayList<>();
            for (Analysis analysis : list) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumActive());
                newList.add(rd);
            }
            //去年
            LambdaQueryWrapper<Analysis> qw2 = new LambdaQueryWrapper<>();
            qw2.between(Analysis::getRecordDate,lastBegin,lastEnd);
            List<Analysis> lastList = analysisMapper.selectList(qw2);
            List<ResultDate> oldList = new ArrayList<>();
            for (Analysis analysis : lastList) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumActive());
                oldList.add(rd);
            }
            Map result = new HashMap();
            result.put("thisYear",newList);
            result.put("lastYear",oldList);
            return result;
        }

        //3.次日留存
        if (begin!=null&&end!=null&&"103".equals(type)&&begin.before(end)){
            //今年
            LambdaQueryWrapper<Analysis> qw1 = new LambdaQueryWrapper<>();
            qw1.between(Analysis::getRecordDate,begin,end);
            List<Analysis> list = analysisMapper.selectList(qw1);
            List<ResultDate> newList = new ArrayList<>();
            for (Analysis analysis : list) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumRetention1d());
                newList.add(rd);
            }
            //去年
            LambdaQueryWrapper<Analysis> qw2 = new LambdaQueryWrapper<>();
            qw2.between(Analysis::getRecordDate,lastBegin,lastEnd);
            List<Analysis> lastList = analysisMapper.selectList(qw2);
            List<ResultDate> oldList = new ArrayList<>();
            for (Analysis analysis : lastList) {
                ResultDate rd = new ResultDate();
                rd.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                rd.setAmount(analysis.getNumRetention1d());
                oldList.add(rd);
            }
            Map result = new HashMap();
            result.put("thisYear",newList);
            result.put("lastYear",oldList);
            return result;
        }
        return null;
    }
}
